package cn.aiyuan.security;


import cn.aiyuan.pojo.Account;
import cn.aiyuan.pojo.AccountRole;
import cn.aiyuan.pojo.Role;
import cn.aiyuan.security.utils.SecurityUser;
import cn.aiyuan.service.AccountRoleService;
import cn.aiyuan.service.AccountService;
import cn.aiyuan.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author Administrator
 */
@Slf4j
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private AccountService accountService;

    @Resource
    private AccountRoleService accountRoleService;

    @Resource
    private RoleService roleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //加载基础用户信息
        Account user = accountService.getOne(new LambdaQueryWrapper<Account>().eq(Account::getAccount,username)
                .eq(Account::getEnable,true));
        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //角色验证
        List<AccountRole> userRoles = accountRoleService.list(new LambdaQueryWrapper<AccountRole>().eq(AccountRole::getAccountId, user.getId()));
        List<Role> roles = roleService.listByIds(userRoles.stream().map(AccountRole::getRoleId).collect(Collectors.toList()));
        List<String> roleCodes = roles.stream().map(Role::getCode).collect(Collectors.toList());
        List<SimpleGrantedAuthority> authorities = getAuthorities(roleCodes);
        SecurityUser customUser = new SecurityUser(user.getAccount(), user.getEncryptedPassword(), authorities);
        //设置当前用户所需信息
        customUser.setId(user.getId());
        customUser.setAccountNum(user.getAccount());
        log.info("用户{}验证通过:",username);
        return customUser;
    }



    private List<SimpleGrantedAuthority> getAuthorities(List<String> roles) {
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        roles.forEach(role-> simpleGrantedAuthorities.add(new SimpleGrantedAuthority(role)));
        return simpleGrantedAuthorities;
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("123456"));
    }
}
